package one.three.thirtyOne;

public class DoubleNode<Item> {

	private Item item;
	private DoubleNode<Item> next;
	private DoubleNode<Item> pre;

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		DoubleNode<Item> c = this;
		while (c != null) {
			sb.append("[" + c.item.toString() + "]");
			c = c.next;
		}
		return sb.toString();
	}

	public void insert(Item item) {

	}

	public static <T> DoubleNode<T> insertHead(DoubleNode<T> l, T t) {
		if (l != null && t != null) {
			DoubleNode<T> n = new DoubleNode<T>();
			n.item = t;
			l.pre = n;
			n.next = l;
			return n;
		}
		return l;
	}

	public static <T> DoubleNode<T> insertTail(DoubleNode<T> l, T t) {
		if (l != null && t != null) {
			DoubleNode<T> n = l;
			while (n.next != null) {
				n = n.next;
			}
			n.next = new DoubleNode<T>();
			n.next.item = t;
			n.next.pre = n;
			return l;
		}
		return l;
	}

	public static <T> DoubleNode<T> deleteHead(DoubleNode<T> l) {
		if (l != null) {
			return l.next;
		}
		return l;
	}

	public static <T> DoubleNode<T> deleteTail(DoubleNode<T> l) {
		if (l != null) {
			if (l.next == null) {
				l = null;
			} else {
				DoubleNode<T> c = l;
				while (c.next.next != null) {
					c = c.next;
				}
				c.next = null;
			}
		}
		return l;
	}

	public static <T> DoubleNode<T> addBefore(DoubleNode<T> l, DoubleNode<T> n, T t) {
		if (l != null && n != null && t != null) {
			DoubleNode<T> c = l;
			while (c != n && c != null) {
				c = c.next;
			}
			if (c != null) {
				DoubleNode<T> newNode = new DoubleNode<T>();
				newNode.item = t;
				c.pre.next = newNode;
				newNode.pre = c.pre;
				newNode.next = c;
				c.pre = newNode;
			}
		}
		return l;
	}

	public static <T> DoubleNode<T> addAfter(DoubleNode<T> l, DoubleNode<T> n, T t) {
		if (l != null && n != null && t != null) {
			DoubleNode<T> c = l;
			while (c != n && c != null) {
				c = c.next;
			}
			if (c != null) {
				DoubleNode<T> newNode = new DoubleNode<T>();
				newNode.item = t;
				newNode.pre = c;
				newNode.next = c.next;
				c.next.pre = newNode;
				c.next = newNode;
			}
		}
		return l;
	}

	public static <T> void delete(DoubleNode<T> l, DoubleNode<T> n) {
		if(l!=null && n!=null) {
			DoubleNode<T> c=l;
			while(c!=n && c!=null) {
				c=c.next;
			}
			if(c!=null) {
				c.pre.next=c.next;
				c.next.pre=c.pre;
			}
		}
	}
	
	public static void main(String[] args) {
		DoubleNode<String> f = new DoubleNode<String>();
		f.item = "a";
		f = DoubleNode.insertTail(f, "b");
		f = DoubleNode.insertTail(f, "c");
		System.out.println(f);

		DoubleNode<String> b = f.next;
		DoubleNode.delete(f, b);
		System.out.println(f);

	}

}
